package com.ming_za.odupdaterserver.core.controller.cmd;

import com.ming_za.odupdaterserver.api.LocalFileResReader;
import com.ming_za.odupdaterserver.api.Updater;
import com.ming_za.odupdaterserver.core.mco_core.API.CmdOperate;
import com.ming_za.odupdaterserver.core.mco_core.Cmd.BasisCmd.ConfirmCmd;
import com.ming_za.odupdaterserver.core.mco_core.Cmd.CmdCreate;
import com.ming_za.odupdaterserver.core.service.ReturnBusinessPackage;
import com.ming_za.odupdaterserver.core.utils.Msg;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

@CmdCreate(cmd = "addRes",explain = "从本地文件(夹)添加资源")
public class addLocalResCmd implements CmdOperate {

    private final ConfirmCmd confirmCmd;

    private void showFormat(){
        Msg.getInstance().soutMsg("&c格式：addRes <路径>");
    }

    private final LocalFileResReader localFileResReader;
    private final Updater updater;

    public addLocalResCmd(ConfirmCmd confirmCmd, LocalFileResReader localFileResReader, Updater updater) {
        this.confirmCmd = confirmCmd;
        this.localFileResReader = localFileResReader;
        this.updater = updater;
    }

    @Override
    public boolean onCommand(String command, String[] args) {

        if (args.length > 1){
            confirmCmd.addConfirm(unused-> localFileResReader.readRes(args[1],(item)->{
                try {
                    Msg.getInstance().info("正在添加资源->" + item.getResAddVo().getClientPath());
                    ReturnBusinessPackage<Long> rbp = updater.addRes(item.getResAddVo(), new FileInputStream(item.getFile()));
                    if (!rbp.isSuccess()){
                        Msg.getInstance().error(rbp.getCode().getDefaultMsg());
                    }
                } catch (FileNotFoundException e) {
                    Msg.getInstance().error(e.getMessage(),e);
                }
            }));
            return true;
        }

        showFormat();

        return false;
    }
}
